package jsonutils

import (
	"bytes"
	jsoniter "github.com/json-iterator/go"
	"github.com/sirupsen/logrus"
)

type JsonUtils struct {
}

func ToJson(v any) (string, error) {

	result, err := ToJsonBytes(v)
	return string(result), err
}

func ToJsonBytes(v any) ([]byte, error) {
	result, err := jsoniter.MarshalIndent(v, "", "  ")
	if err != nil {
		logrus.Println(err)
		return []byte("{}"), err
	}
	return result, nil
}

func FromJson(str string, obj any) error {

	d := jsoniter.NewDecoder(bytes.NewBufferString(str))
	d.UseNumber()
	err := d.Decode(obj)
	if err != nil {
		logrus.Error(err)
	}
	return err
}
func FromJsonByte(inbyte []byte, obj any) error {
	d := jsoniter.NewDecoder(bytes.NewBuffer(inbyte))
	d.UseNumber()
	err := d.Decode(obj)
	if err != nil {
		logrus.Error(err)
	}
	return err
}
func ToJsonStr(v any) string {
	result, err := jsoniter.Marshal(v)
	if err != nil {
		logrus.Error(err)
		return "{}"
	}
	return string(result)
}

func ToJsonPretty(v any) string {
	result, err := jsoniter.MarshalIndent(v, "", "     ")
	if err != nil {
		logrus.Error(err)
		return "{}"
	}
	return string(result)
}

func FromJsonStr(param []byte) any {
	var ret any
	_ = jsoniter.Unmarshal(param, &ret)
	return ret
}

func MapFromJson(param string) (m *map[string]any, err error) {
	m = &map[string]any{}
	err = FromJson(param, m)
	return m, err
}

func Str2JsonPretty(txt string) string {
	v := FromJsonStr([]byte(txt))
	return ToJsonPretty(v)
}

func Byte2JsonPretty(b []byte) string {
	v := FromJsonStr(b)
	return ToJsonPretty(v)
}
